package lsieun.utils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class ContainerUtils {
    private static final DateFormat df = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss.SSS");
    private static final Map<String, byte[]> map = new HashMap<>();

    public static void addClass(String className, byte[] bytes) {
        map.put(className, bytes);
    }

    public static void compareClass(String className, byte[] bytes) {
        byte[] origin_bytes = map.get(className);
        if (origin_bytes == null) return;
        if (bytes == null) {
            map.remove(className);
            return;
        }
        boolean isEqual = Arrays.equals(origin_bytes, bytes);
        if (isEqual) {
            map.remove(className);
            return;
        }

        String newName = className.replace('/', '.');
        Date now = new Date();
        String dateStr = df.format(now);
        String filenameA = String.format("%s.%s.%s.class", newName, dateStr, "A");
        String filenameB = String.format("%s.%s.%s.class", newName, dateStr, "B");
        dump(filenameA, origin_bytes);
        dump(filenameB, bytes);
        System.out.println("Diff: " + filenameA);
        System.out.println("Diff: " + filenameB);
    }

    private static void dump(String filename, byte[] bytes) {
        String user_home = System.getProperty("user.home");
        String dir_path = user_home + File.separator + "compare_class";
        File dirFile = new File(dir_path);
        dirFile.mkdirs();
        String filepath = dir_path + File.separator + filename;
        try (
                FileOutputStream fout = new FileOutputStream(filepath);
                BufferedOutputStream bout = new BufferedOutputStream(fout)
        ) {
            bout.write(bytes);
            bout.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}